package com.internal.fileDataModel;

import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Iterator;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.ListableBeanFactory;


public class TreeDirectory implements Iterable<Node>{
	
	final static Logger log = Logger.getLogger(TreeDirectory.class);
	private Node root;
	private ArrayList<Node> lista;
	public Node getRoot() {
		return root;
	}

	public void setRoot(Node root) {
		this.root = root;
	}
	
	public void insert(Path path){
		
		if(root == null){
			root = new Node(path);
			log.info(root.getHasCode());
		}
		else  {
			int hashParent = path.getParent().hashCode();
			insert(path, hashParent, root);
		}
	}
	
	public void insert(Path path, int parent, Node n){
		
		if(n.getHasCode() == parent)
		{
			Node node = new Node(path);
			n.getParent().add(node);
		}else {
			for (Node node: n.getParent()) {
					insert(path,parent,node);
				}
		}
	}
	
	public boolean contains(Path path){
		return contains(path,root,false);
	}
	
	public boolean contains(Path path, Node node,boolean find){
		
		for (Node n : node.getParent()) {
			if(n.getPath().equals(path))
				find = true;
			else contains(path, n, find);
		}
		return find;
	}
	
	public ArrayList<Node> lista (Node n, ArrayList<Node> buff){
		for (Node node: n.getParent()) {
			buff.add(node);
			lista(node, buff);
		}
		return buff;
	}
	
	public ArrayList<Node> lista(){
		lista = new ArrayList<Node>();
		return lista(root,lista);
	}
	
	
	public StringBuffer print(Node n, StringBuffer buff){
		for (Node node: n.getParent()) {
			buff.append(node+"\n");
			print(node, buff);
		}
		return buff;
	}
	
	public String toString(){
		return print(root, new StringBuffer()).toString();
	}

	@Override
	public Iterator<Node> iterator() {
		
		return root.getParent().iterator();
	}

}
